import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/record/points_entity.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:ball_lion/module/record/points_logic.dart';
import 'package:ball_lion/entity/record/football/zq_schedule_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/ladder_tab_bar.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'items/points_chart.dart';
import 'items/points_data_line.dart';
import 'items/schedule_item.dart';

class PointsPage extends StatefulWidget {
  PointsPage({super.key, this.leagueId, required this.tag})
      : logic = Get.put(PointsLogic(leagueId, seasonTag: tag), tag: tag);

  final int? leagueId;
  final String tag;
  final PointsLogic logic;

  @override
  State<PointsPage> createState() => _PointsPageState();
}

class _PointsPageState extends State<PointsPage>
    with AutomaticKeepAliveClientMixin {
  late final PointsLogic logic = widget.logic;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<PointsLogic>(
        tag: widget.tag,
        builder: (logic) {
          return VisibilityDetector(
            key: Key(widget.tag),
            onVisibilityChanged: (VisibilityInfo info) {
              logic.visible = !info.visibleBounds.isEmpty;
            },
            child: LoadingWidget<int>(
              isLoading: logic.isLoading,
              data: logic.entity?.matchStages?.length,
              child: () => EasyRefresh(
                controller: logic.refreshController,
                onRefresh: logic.getData,
                child: SingleChildScrollView(
                  child: Container(
                    constraints: BoxConstraints(minHeight: Get.height),
                    child: Column(
                      children: [
                        _buildMatchWidget(),
                        if (logic.entity?.introduce.hasValue == true)
                          _buildIntroduceWidget()
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        });
  }

  Widget _buildMatchWidget() {
    return Column(
      children: List.generate(
          logic.matches?.length ?? 0,
          (index) => Column(children: [
                if (logic.matches?[index].road == null)
                  Container(
                    width: Get.width,
                    color: Colours.greyF2F3F7,
                    alignment: Alignment.center,
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: QsText(logic.matches?[index].name ?? "",
                        fontSize: 13, fontWeight: FontWeight.w500),
                  ),
                if (logic.channel.recordType == 0)
                  _zqDivide(logic.matches?[index]),
                if (logic.channel.recordType == 1)
                  _lqDivide(logic.matches?[index])
              ])),
    );
  }

  Widget _buildIntroduceWidget() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 50, top: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.only(left: 16, right: 16),
            child: QsText("赛事介绍", fontSize: 14, fontWeight: FontWeight.w500),
          ),
          Container(height: 4),
          Padding(
            padding: const EdgeInsets.only(left: 8, right: 8),
            child: Html(
              data: logic.introduce(logic.entity?.introduce?.trim() ?? ""),
              style: {
                "div": Style(
                  fontSize: FontSize(14),
                  color: Colours.N8,
                  lineHeight: const LineHeight(1.6),
                  textAlign: TextAlign.justify,
                  letterSpacing: -0.25,
                ),
                "p": Style(margin: Margins(bottom: Margin(5)))
              },
            ),
          )
        ],
      ),
    );
  }

  Widget _lqDivide(MatchStage? stage) {
    if (stage?.road != null) {
      return PointsChart.basketball(road: stage?.road)
          .paddingSymmetric(vertical: 8);
    } else if (stage?.schedules.hasValue == true) {
      return Column(
          children: List.generate(
              stage?.schedules?.length ?? 0,
              (index) => ScheduleCell(
                    schedules: stage?.schedules?[index],
                    index: index,
                    recordType: logic.channel.recordType,
                  )));
    } else {
      return _points(stage);
    }
  }

  Widget _zqDivide(MatchStage? stage) {
    if (stage?.road != null) {
      return Container(
        color: Colours.white,
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: PointsChart(
            road: stage?.road, recordType: logic.channel.recordType),
      );
    } else if (stage?.matchGroups != null) {
      return Column(
        children: List.generate(stage?.matchGroups?.length ?? 0, (index) {
          if (stage?.matchGroups?[index].scheduleGroups?.hasValue == true) {
            return Column(
                children: List.generate(
                    stage?.matchGroups?[index].scheduleGroups?.length ?? 0,
                    (childIndex) => _doubleMatch(
                        stage?.matchGroups?[index].scheduleGroups?[childIndex],
                        childIndex)));
          } else if (stage?.matchGroups?[index].teams?.length != 0) {
            return _pointsList(stage?.matchGroups?[index]);
          } else {
            return Container();
          }
        }),
      );
    } else {
      return Container();
    }
  }

  Widget _pointsList(MatchGroup? pointsList) {
    var qualify = logic.qualification(pointsList?.qualify ?? []);
    return Container(
      color: Colours.white,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 10, bottom: 10, right: 16),
            child: pointsList?.name != "" && pointsList?.name != "联赛"
                ? DataLine(
                    headType: pointsList?.name ?? '球队',
                    isHeader: true,
                    recordType: logic.channel.recordType)
                : DataLine(
                    headType: "球队",
                    isHeader: true,
                    recordType: logic.channel.recordType),
          ),
          Column(
            children:
                List.generate(pointsList?.teams?.length ?? 0, (childIndex) {
              if (childIndex == 0) logic.qualifyIndex = 0;
              if (qualify.hasValue) {
                if (childIndex >
                        ((qualify[logic.qualifyIndex].endRank ?? 10000) - 1) &&
                    logic.qualifyIndex <
                        ((pointsList?.qualify?.length ?? 0) - 1)) {
                  logic.qualifyIndex += 1;
                }
              }
              return DataLine(
                  recordType: logic.channel.recordType,
                  index: childIndex,
                  qualify:
                      qualify.isNotEmpty ? (qualify[logic.qualifyIndex]) : null,
                  team: pointsList?.teams?[childIndex]);
            }),
          ),
        ],
      ),
    );
  }

  Widget _points(MatchStage? stage) {
    var tab = ["常规赛排行", "分区排行"];
    var type = 3;
    if (stage?.matchGroups != null && stage?.areaGroups != null) {
      type = 2;
    } else if (stage?.matchGroups == null && stage?.areaGroups != null) {
      type = 1;
    } else if (stage?.matchGroups != null && stage?.areaGroups == null) {
      type = 0;
    }
    return type == 3
        ? Container()
        : Column(children: [
            if (type == 2)
              Container(
                color: Colours.greyF2F3F7,
                padding: const EdgeInsets.only(top: 10),
                child: TabBlock(
                    selectLabelStyle: TabStyle(color: Colours.main),
                    tabs: tab.map((e) => QsText(e)).toList(),
                    pages: List.generate(
                        2,
                        (index) => Column(
                            children: List.generate(
                                index == 0
                                    ? (stage?.matchGroups?.length ?? 0)
                                    : stage?.areaGroups?.length ?? 0,
                                (i) => _pointsList(index == 0
                                    ? (stage?.matchGroups?[i])
                                    : stage?.areaGroups?[i]))))),
              ),
            if (type <= 1) ...[
              Container(
                height: 38,
                alignment: Alignment.center,
                child: QsText(tab[type].substring(0, tab[type].length - 2),
                    fontSize: 13, fontWeight: FontWeight.w600),
              ),
              Column(
                  children: List.generate(stage?.matchGroups?.length ?? 0,
                      (index) => _pointsList(stage?.matchGroups?[index])))
            ]
          ]);
  }

  Widget _doubleMatch(ScheduleGroup? entity, index) {
    Schedules head = Schedules(
        leftId: entity?.leftId,
        rightId: entity?.rightId,
        leftLogo: entity?.leftLogo,
        rightLogo: entity?.rightLogo,
        leftName: entity?.leftName,
        rightName: entity?.rightName,
        leftScoreEnd: (entity?.leftScore ?? 0) +
            (entity?.leftScoreOT ?? 0) +
            (entity?.leftScorePK ?? 0),
        rightScoreEnd: (entity?.rightScore ?? 0) +
            (entity?.rightScoreOT ?? 0) +
            (entity?.rightScorePK ?? 0),
        status: entity?.schedules?.last.status);
    return (entity?.schedules?.length ?? 0) > 1
        ? Container(
            color: Colours.white,
            child: Column(
              children: [
                ScheduleCell(
                    schedules: head, index: 0, needColor: false, recordType: 0),
                Container(
                  clipBehavior: Clip.antiAlias,
                  margin: const EdgeInsets.symmetric(horizontal: 8),
                  decoration: BoxDecoration(
                      color: Colours.greyF2F3F7,
                      borderRadius: BorderRadius.circular(8)),
                  child: Column(
                    children: [
                      ScheduleCell(
                          schedules: entity?.schedules?[0],
                          index: 1,
                          padding: 8,
                          recordType: 0),
                      ScheduleCell(
                          schedules: entity?.schedules?[1],
                          index: 1,
                          padding: 8,
                          recordType: 0),
                    ],
                  ),
                )
              ],
            ),
          )
        : ScheduleCell(
            schedules: entity?.schedules?[0], index: index, recordType: 0);
  }

  @override
  bool get wantKeepAlive => true;
}
